package com.platform.utils;

import com.alibaba.druid.support.logging.Log;
import com.alibaba.druid.support.logging.LogFactory;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.ByteArrayRequestEntity;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;

import java.util.Map;

/*
* 微信公众号工具类
* */
public class WeChatMpUtils {
    private static Log logger = LogFactory.getLog(WeChatMpUtils.class);


    /*
    * 生成永久二维码
    * */
    public static String createForeverTicket(String accessToken, String sceneStr) throws Exception {


        String ticke = null;

        // 拼接请求地址
        String requestUrl = " https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=TOKEN";
        requestUrl = requestUrl.replace("TOKEN", getAccessToken());

        // 需要提交json数据
        JSONObject data = new JSONObject();
        data.put("action_name", "QR_LIMIT_STR_SCENE");
        JSONObject actionInfo = new JSONObject();
        JSONObject scene = new JSONObject();
        scene.put("scene_str", sceneStr);
        actionInfo.put("scene", scene);
        data.put("action_info", actionInfo);

        // 创建永久带参二维码
        Map<String, Object> resultMap = httpClientPost(requestUrl, data.toString());
        if (resultMap.get("ticket") != null)
        {
            ticke = resultMap.get("ticket").toString();
            logger.info("永久带参二维码ticket成功=" + ticke);
         }else{
            String err = resultMap.get("errcode").toString();
            String errormsg = resultMap.get("errmsg").toString();
            logger.error("永久带参二维码ticket失败失败errcode=" + err + "errmsg=" + errormsg);
        }
        return ticke;
    }

    private static String getAccessToken() throws Exception{
        String app_id= ResourceUtil.getConfigByName("mp.appId").trim();
        String app_secret=ResourceUtil.getConfigByName("mp.secret").trim();
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + app_id + "&secret=" + app_secret;
        Map<String, Object> accessTokenMap = httpClientGet(url);
        logger.info("accessTokenMap"+accessTokenMap);
        return accessTokenMap.get("access_token").toString();
    }

    private static Map<String, Object> httpClientPost(String url, String params) throws Exception {
        HttpClient client = new HttpClient();
        client.getParams().setContentCharset("UTF-8");
        PostMethod httpPost = new PostMethod(url);
        try {
            RequestEntity requestEntity = new ByteArrayRequestEntity(params.getBytes("utf-8"));
            httpPost.setRequestEntity(requestEntity);
            client.executeMethod(httpPost);
            String response = httpPost.getResponseBodyAsString();
            Map map = JSON.parseObject(response,Map.class);
            return map;
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            httpPost.releaseConnection();
        }
    }
    private static Map<String, Object> httpClientGet(String url) throws Exception {
        HttpClient client = new HttpClient();
        client.getParams().setContentCharset("UTF-8");
        GetMethod httpGet = new GetMethod(url);
        try {
            client.executeMethod(httpGet);
            String response = httpGet.getResponseBodyAsString();
            Map map = JSON.parseObject(response,Map.class);
            logger.info("httpClient Map"+map);
//            Map<String, Object> map = JsonUt.fromJson(response, Map.class);
            return map;
        } catch (Exception e) {
            throw e;
        } finally {
            httpGet.releaseConnection();
        }
    }
}
